//
//  Extension+More.swift
//  NetworkKit
//
//  Created by TSYH on 2024/3/15.
//

import Foundation
import CryptoKit

extension FileManager {
    func filePath(with fileName: String) -> URL? {
        guard let documentUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            return nil
        }
        return documentUrl.appendingPathComponent(fileName)
    }
    
    func fileData(with fileName: String) -> Data? {
        guard let filePath = filePath(with: fileName) else {
            return nil
        }
        if fileExists(atPath: filePath.absoluteString.localFilePath) {
            return try? Data(contentsOf: filePath)
        }
        return nil
    }
    
    func fileExists(with fileName: String) -> Bool {
        guard let filePath = filePath(with: fileName) else {
            return false
        }
        return fileExists(atPath: filePath.absoluteString.localFilePath)
    }
    
    func write(data: Data, to fileName: String) {
        guard let filePath = filePath(with: fileName) else {
            return
        }
        try? data.write(to: filePath)
    }
    
    func remove(fileName: String) {
        guard let filePath = filePath(with: fileName) else {
            return
        }
        try? removeItem(at: filePath)
    }
}

extension String {
    var md5String: String? {
        guard let data = data(using: .utf8) else {
            return nil
        }
        
        let digest = Insecure.MD5.hash(data: data)
        return digest.map {
                    String(format: "%02hhx", $0)
        }.joined()
    }
    
    var localFilePath: String {
        var path = self
        if path.lowercased().hasPrefix("file://") {
            path.removeFirst("file://".count)
        }
        return path
    }
}
